package com.example.ui.register;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.huashangapp.R;
import com.example.net.NetRequest;
import com.example.ui.HSCallBack;
import com.example.util.Util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Instrumentation.ActivityResult;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("ValidFragment")
public class Register_Activity02 extends Activity{
	private String tellphone;
	private HSCallBack callback;
	private TextView ra3_title, ra3_tellphone;
	private Button ra3_next, ra3_return,sandMesg;
	private static EditText ra3_code;
	private String mobile;
	public static boolean canNext=false;
	private static Context context;
	private String res;
	View v;
	private Handler h;
	
	 int minute = -1;
	 int second = -1;
	TextView timeView;
	static Timer timer;
	TimerTask  timerTask;
	SmsContent content = new SmsContent(this, new Handler());
	Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			System.out.println("handle!");
			if (minute == 0) {
				if (second == 0) {
					minute = -1;
					second = -1;
					timeView.setText("");
					if (timer != null) {
						timer.cancel();
						timer = null;
					}
					if (timerTask != null) {
						timerTask = null;
					}
					timeView.setVisibility(View.GONE);
					sandMesg.setVisibility(View.VISIBLE);
				}else if(second>0){
					second--;
					if (second >= 10) {
						timeView.setText("接收短信大约需要"+ second+"秒钟");
					}else {
						timeView.setText("接收短信大约需要0"+ second+"秒钟");
					}
				}
			}else {
				if (second == 0) {
					second =59;
					minute--;
					if (minute >= 10) {
						timeView.setText("接收短信大约需要"+ second+"秒钟");
					}else {
						timeView.setText("接收短信大约需要"+ second+"秒钟");
					}
				}else if(second>0) {
					second--;
					if (second >= 10) {
						if (minute >= 10) {
							timeView.setText("接收短信大约需要"+ second+"秒钟");
						}else {
							timeView.setText("接收短信大约需要"+ second+"秒钟");
						}
					}else {
						if (minute >= 10) {
							timeView.setText("接收短信大约需要0"+ second+"秒钟");
						}else {
							timeView.setText("接收短信大约需要0"+ second+"秒钟");
						}
					}
				}
			}
		};
	};
	
	public Register_Activity02(){
		
	}
	public Register_Activity02(String tellphone){
		this.tellphone=tellphone;
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.a_register_item2);
		init();
		context=Register_Activity02.this;
	}
	public void sandTime(){
		getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, content);
		cr=getContentResolver();
		if (minute == -1 && second == -1) {
			minute = 1;
			second =0;
		}
		timeView.setText("接收短信大约需要59秒钟");
		timerTask = new TimerTask() {
			@Override
			public void run() {
				Message msg = new Message();
				msg.what = 0;
				handler.sendMessage(msg);
			}
		};
		timer = new Timer();
		timer.schedule(timerTask,0,1000);
	}
	private String password;
	@Override
	protected void onStart() {
		context=Register_Activity02.this;
		sandTime();
		 h = new Handler() {
				

				public void handleMessage(android.os.Message msg) {
					switch (msg.what) {
					case 1:
						Intent intent = new Intent();
						intent.setClass(context,RegisterActivity4.class);
						intent.putExtra("password",password);
						startActivity(intent);
						finish();
						break;
					case 2:			
						new AlertDialog.Builder(context).setTitle("提示").setMessage("验证码错误，请重试").show();
						break;
					case 3:
						ra3_code.setText(smsContent);
						new AlertDialog.Builder(context)
						.setTitle("验证短信")  
						.setMessage("您的初始密码为手机后六位:"+password+"是否提交提交验证")
						.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								if (timer != null) {
									timer.cancel();
									timer = null;
								}
								if (timerTask != null) {
									timerTask = null;
								}
								minute=-1;
								second=-1;
								timeView.setText("");
								timeView.setVisibility(View.VISIBLE);
								sandMesg.setVisibility(View.GONE);
								return;
							}
						})
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										if (timer != null) {
											timer.cancel();
											timer = null;
										}
										if (timerTask != null) {
											timerTask = null;
										}
										minute=-1;
										second=-1;
										timeView.setText("");
										timeView.setVisibility(View.VISIBLE);
										sandMesg.setVisibility(View.GONE);
									match();
									}
								}).show();
						break;
					case 4:
						new AlertDialog.Builder(context).setTitle("提示").setMessage("是否返回重新验证手机号码")
						.setNegativeButton("否", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								
							}
						})
						.setPositiveButton("是",new DialogInterface.OnClickListener(){
							@Override
							public void onClick(DialogInterface dialog, int which) {
								Intent intent = new Intent(Register_Activity02.this,RegisterActivity01.class);
								startActivity(intent);
								finish();
							}
						}).show();
						break;
					default:
						break;
					}

				};
		 };
		super.onStart();
	}
	private void init() {		
		tellphone=getIntent().getStringExtra("mobile");
		password=tellphone.substring(tellphone.length()-6,tellphone.length());
		ra3_tellphone = (TextView) findViewById(R.id.ar3_tellphone);
		ra3_title = (TextView) findViewById(R.id.register_title);
		ra3_next = (Button) findViewById(R.id.register_next);
		ra3_return = (Button) findViewById(R.id.register_return);
		ra3_code = (EditText) findViewById(R.id.ar3_code);
		
		ra3_title.setText("获取验证码(3/5)");
		ra3_tellphone.setText("短信已发送到+86" + tellphone);
		timeView = (TextView)findViewById(R.id.myTime);
		sandMesg=(Button)findViewById(R.id.send);
		ra3_return.setOnClickListener(ra3_ocl);
		ra3_next.setOnClickListener(ra3_ocl);
		sandMesg.setOnClickListener(ra3_ocl);
	}
	private Builder bulider;
	private AlertDialog infoad;
	OnClickListener ra3_ocl = new OnClickListener() {
		@Override
		public void onClick(View v) {
			
			switch (v.getId()) {
			case R.id.register_next:
					match();
				break;
			case R.id.register_return:
				h.sendEmptyMessage(4);
				break;
			case R.id.send:
				sandMesg.setVisibility(View.GONE);
				timeView.setVisibility(View.VISIBLE);
				getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, content);
				sandTime();
				new Thread(r1_run).start();
				break;
			default:
				break;
			}
		}
	};
	private Runnable r1_run = new Runnable() {
		@Override
		public void run() {
			res = NetRequest.postRequest2Again(tellphone);
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(res);
				String response = jsonObject.getString("response");
				if (response.equals("true")) {
				}else{
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	};
	Runnable r3_run = new Runnable() {

		@Override
		public void run() {
			res = NetRequest.postRequest3(tellphone, ra3_code.getText().toString());
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(res);
				String response = jsonObject.getString("response");
				if (response.equals("true")) {
					h.sendEmptyMessage(1);
				} else if (response.equals("code_error")) {
					h.sendEmptyMessage(2);
				}
			} catch (JSONException e) {
				
				e.printStackTrace();
			}
		}
	};
	private void match() {
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (timerTask != null) {
			timerTask = null;
		}
		String code = ra3_code.getText().toString();
			int codeLength = code.length();
				if (codeLength != 6) {
					Toast.makeText(context, "验证码输入错误", Toast.LENGTH_LONG).show();
					return;
				} else {
					code = ra3_code.getText().toString();
					new Thread(r3_run).start();
					return;
				}
	}
	private ContentResolver cr;

	
	 private String smsContent;
class SmsContent extends ContentObserver{

	public SmsContent(Handler handler) {
		super(handler);
	}
	public SmsContent(Register_Activity02 register_Activity02, Handler handler) {
		super(handler);
	}
	
		@Override
		public void onChange(boolean selfChange) {
		super.onChange(selfChange);
		  // 读取收件箱中指定号码的短信
		 Cursor cursor = null;// 光标
		  cursor = ((Activity) context).managedQuery(Uri.parse("content://sms/inbox"), new String[] { "_id", "address", "body", "read" }, "address like ? and read=? and body like ? ",
		                                 new String[] {"%106%","0","%华商学习网%"}, "date desc");
		  if (cursor != null) {// 如果短信为未读模式
		   if (cursor.moveToFirst()) {
			   String smsbody = cursor.getString(cursor.getColumnIndex("body"));
			    String regEx = "[^0-9]";
			    Pattern p = Pattern.compile(regEx);
			    Matcher m = p.matcher(smsbody.toString());
			    smsContent = m.replaceAll("").trim().toString();
			    h.sendEmptyMessage(3);
			    ContentValues values = new ContentValues();
			    values.put("read", "1"); 
			    getContentResolver().update(Uri.parse("content://sms/inbox"), values, " _id=?", new String[]{""+cursor.getInt(0)});
		   		}
		   cr.unregisterContentObserver(content);
		 	}
		  
		 }
	}
}
